package net.zhengxinyun.performance.service.exportService;

import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.dto.ExcelDTO;
import net.zhengxinyun.performance.entity.DepartmentEntity;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.excel.ExcelMapper;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ExcelDtoServiceImpl implements ExcelDtoService {


    @Autowired
    private ExcelMapper excelMapper;
    @Autowired
    private DepartmentEntityMapper departMapper;

    @Override
    public List<ExcelDTO> queryData(String dto,Integer avail) {
        return excelMapper.queryData(dto,avail);
    }

    @Override
    public int saveData(List dto) {
        return excelMapper.saveData(dto);
    }

    @Override
    public int updateExcelData(ExcelDTO dto) {
        if(StringUtils.isNotBlank(dto.getCell23()) )
        {

            dto.setAvail(1);

            DepartmentEntity entity = departMapper.selectByCode(dto.getCell23());
            //dto.setName23(entity.getDepartment());
            dto.setRemark("牵头单位已手动配成【"+entity.getDepartment()+"】");
        }else {
            dto.setRemark(null); // 不更新
            dto.setAvail(0);
        }

        return excelMapper.updateExcelData(dto);
    }

    /**
     * 匹配表头
     * @param sheet
     * @return
     */
    @Override
    public String matchExcelHead(Sheet sheet,String[] excelHead) {
        Row tableHeader = sheet.getRow(0);//
        for (int i = 0; i < excelHead.length; i++) {

            tableHeader.getCell(i).setCellType(Cell.CELL_TYPE_STRING);
            String callValue =  tableHeader.getCell(i).getStringCellValue();
            callValue = callValue.trim();
            if(!excelHead[i].equals(callValue)){
                System.out.println("表头【" + callValue + "】错误，该处表头应为【" + excelHead[i] + "】");
                return "表头【"+callValue+"】错误，该处表头应为【"+excelHead[i]+"】";
            }
        }
        return "ok";
    }
}
